import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { DictContext } from '../../../context/context';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SyncOutlined, CloseOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';
import { useParams, useNavigate } from 'react-router-dom';
import { addData, listData, updateData, delData,getData } from '../../../api/dict/data'
import { getType, optionselect } from '../../../api/dict/type';

function DictData() {
    const { useDict, addDateRange} = useContext(DictContext);
    const { sys_normal_disable } = useDict('sys_normal_disable');
    const navigate = useNavigate();
    const columns =[
        {
            title: '字典编码',
            dataIndex: 'dictCode',
            key: 'dictCode',
        },
        {
            title: '字典标签',
            dataIndex: 'dictLabel',
            key: 'dictLabel',
        },
        {
            title: '字典值',
            dataIndex: 'dictValue',
            key: 'dictValue',
        },
        {
            title: '字典状态',
            dataIndex: 'status',
            key: 'status',
            render: (text, record) => <DictTag dictType="sys_normal_disable" value={text} options={sys_normal_disable} ></DictTag>
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
        },  {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        }, {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                            <Space size="middle">
                            <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
                            <Popconfirm
                                title="删除确认"
                                description={`是否确认删除字典编号为 ${record.dictCode} 的数据项？`}
                                onConfirm={() => handleDelete(record)}
                                onCancel={delCancel}
                                okText="确定"
                                cancelText="取消"
                            >
                            <Button type='link'>删除</Button>
                            </Popconfirm>
                            </Space>
                        ),
        }
    ];
  const { dictId } = useParams();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [queryParams, setQueryParams] = useState({
    pageNum: 1,
    pageSize: 10,
    dictType: dictId,
  })
  const [total, setTotal] = useState(0);
  const [searchForm] = Form.useForm();
  const [formAdd] = Form.useForm();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [single, setSingle] = useState(true);
  const [multiple, setMultiple] = useState(true);
  const [ids, setIds] = useState([]);
  const [typeOptions, setTypeOptions] = useState([]);
  const[title,setTitle] = useState('');
  const [open, setOpen] = useState(false);

  const onSelectChange = newSelectedRowKeys => {
    //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    setSingle(newSelectedRowKeys.length != 1) ;
    setMultiple(!newSelectedRowKeys.length);
    setIds(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleDelete = (record) => {
    const dictCode = record?.dictCode || ids;
    delData(dictCode).then(res => {
      if (res.code == 200) {
        message.success('删除成功');
        handleQuery();
      } else {
        message.error(res.msg);
      }
    });
  }

  const handleUpdate = (record) => {
    const dictCode = record?.dictCode || ids;
    getData(dictCode).then(res => {
      if (res.code == 200) {
        formAdd.setFieldsValue(res.data);
        setOpen(true);
      } else {
        
      }

  });
}

  // 处理查询
  // 处理查询
  const handleQuery = () => {
    // 设置加载状态为true
    // 调用listData函数，传入queryParams参数，获取数据
    setLoading(true);
      // 如果返回的code为200，表示查询成功
    listData(queryParams).then(res => {
        // 设置数据
      if (res.code == 200) {
        // 设置总条数
        setData(res.rows);
        setTotal(res.total);
        // 否则，显示错误信息
      } else {
        message.error(res.msg);
      // 设置加载状态为false
      }
      setLoading(false);
    });
  }

  useEffect(() => {
    console.log(queryParams);
    getTypes(queryParams.dictType);
    getTypeOptions();
  }, [queryParams]);

//   useEffect(() => {
//     handleQuery();
//   },[queryParams])

  const onChange = (pagination, filters, sorter) => {
    setQueryParams({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
  }

  const delCancel = () => {
    message.info('取消删除');
  }

  function getTypes(dictId) {
    getType(dictId).then(res => {
        queryParams.dictType = res.data.dictType
        searchForm.setFieldsValue({ dictType: dictId })
        handleQuery()
    })
}

function getTypeOptions() {
    optionselect().then(res => {
        setTypeOptions(res.data)
    })
}

  const handleSearch = (values) => {
    console.log('===handleSearch====',values);
    setQueryParams( preState => ({
        ...preState,
        ...values,
      }));
  }

  const handleOk = () => {
    if(formAdd.getFieldValue().dictCode  == undefined){
        formAdd.validateFields().then(values => {
            console.log('====handleOk====',values);
            addData(values).then(res => {
                if (res.code == 200) {
                    message.success('添加成功');
                    handleQuery();
                    setOpen(false);
                } else {
                    message.error(res.msg);
                }
            })
        });
    } else {
        formAdd.validateFields().then(values => {
            console.log('====handleOk====',values);
            updateData(formAdd.getFieldValue()).then(res => {
                if (res.code == 200) {
                    message.success('修改成功');
                    handleQuery();
                    setOpen(false);
                } else {
                    message.error(res.msg);
                }
            })
        });
    }

  }

  const handleCancel = () => {
    setOpen(false);
  }

  const handleAdd = () => {
    setOpen(true);
    setTitle('添加字典数据');
    formAdd.resetFields();
    formAdd.setFieldsValue({ dictType: queryParams.dictType })
  }

  const handleClose = () => {
    navigate('/system/dict/index')
  }
  return (
    <div>
        <Row gutter={[16, 16]}  style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
                <Form form={searchForm} layout='inline' onFinish={handleSearch}>
                    <Form.Item label='字典名称' name='dictType'>
                        <Select style={{ width: 120 }} options={typeOptions} fieldNames={{ label: 'dictName', value: 'dictId' }} />
                    </Form.Item>
                    <Form.Item label='字典标签' name='dictLabel'>
                        <Input placeholder='请输入字典标签' />
                    </Form.Item>
                    <Form.Item label='状态' name='status'>
                        <Select style={{ width: 120 }} options={sys_normal_disable.value} />
                    </Form.Item>
                    <Form.Item>
                        <Button type='primary' htmlType='submit'>查询</Button>
                    </Form.Item>
                </Form>
            </Col>
            </Row>
            <Row gutter={[16, 16]}  style={{marginBottom: '10px', width: '100%'}}>
            <Col span={24}>
                <Space>
                <Button type='primary' onClick={() => { handleAdd() }} icon={<PlusOutlined />}>添加</Button>
                <Button color="green" variant="filled" disabled={single} onClick={() => { handleUpdate() }} icon={<EditOutlined />}>修改</Button>
                <Button color="danger" variant="filled" disabled={multiple} onClick={() => { handleDelete() }} icon={<DeleteOutlined />}>删除</Button>
                <Button  color="orange" variant="filled" icon={<CloseOutlined />} onClick={() => handleClose()}>关闭</Button>
                </Space>
            </Col>
        </Row>

        <Table loading={loading} rowSelection={rowSelection} dataSource={data} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.dictCode} onChange={onChange}/>
            <Modal title={title} open={open} onOk={handleOk} onCancel={handleCancel}>
                <Form form={formAdd} layout='horizontal' style={{marginTop: '15px'}} labelCol={{ span: 5 }} >
                    <Form.Item label='字典类型' name='dictType'>
                        <Input disabled placeholder='请输入字典类型' />
                    </Form.Item>
                    <Form.Item label='字典标签' name='dictLabel'>
                        <Input placeholder='请输入字典标签' />
                    </Form.Item>
                    <Form.Item label='字典键值' name='dictValue'>
                        <Input placeholder='请输入字典键值' />
                    </Form.Item>
                    <Form.Item label='样式属性' name='cssClass'>
                        <Input placeholder='请输入样式属性' />
                    </Form.Item>
                    <Form.Item label='字典排序' name='dictSort'>
                        <InputNumber min={0} placeholder='请输入字典排序' />
                    </Form.Item>
                    <Form.Item label='回显样式' name='listClass'>
                        <Input placeholder='请输入回显样式' />
                    </Form.Item>
                    <Form.Item label='状态' name='status'>
                        <Select style={{ width: 120 }} options={sys_normal_disable.value} />
                    </Form.Item>
                    <Form.Item label='备注' name='remark'>
                        <Input.TextArea placeholder='请输入备注' />
                    </Form.Item>
                </Form>
            </Modal>
    </div>
  );
}

export default DictData;